package org.example.oauth2.client;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Controller
public class HelloController {

    @Autowired
    RestTemplate restTemplate;

    /**
     * 这段代码跟前面的都差不多，就是请求参数不一样而已，参数 grant_type 的值为 client_credentials。
     */
    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("client_id", "clientId_1");
        map.add("client_secret", "secret_1");
        map.add("grant_type", "client_credentials");
        Map<String,String> resp = restTemplate.postForObject("http://localhost:8081/oauth/token", map, Map.class);
        System.out.println(resp);
        String access_token = resp.get("access_token");
        System.out.println(access_token);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + access_token);
        HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
        ResponseEntity<String> entity = restTemplate.exchange("http://localhost:8082/hello", HttpMethod.GET, httpEntity, String.class);
        return entity.getBody();
    }
}
